<!-- 机房分组号源设置 -->
<template>
  <div class="payment-box">
    <strong>机房号源设置</strong>
    <div class="form_wrap">
      <el-form :model="formData" :rules="rules" inline ref="checkform">
        <el-form-item label="医院名称" prop="hospitalCode">
          <el-select size="small" v-model="formData.hospitalCode" filterable placeholder="请选择" @change="handleChange('hospital')">
            <el-option
              v-for="(item,index) in mx_hospitalList"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="影像区域">
          <el-select size="small" v-model="formData.depArea" placeholder="请选择" clearable @change="handleChange('depArea')">
            <el-option
              v-for="(item,index) in depAreaOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查部门">
          <el-select size="small" v-model="formData.dep" placeholder="请选择" clearable @change="handleChange('dep')">
            <el-option
              v-for="(item,index) in scheduledDepOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机房分组" prop="checkGroup">
          <el-select
            size="small"
            v-model="formData.checkGroup"
            @change="checkGroupChange"
          >
            <el-option
              v-for="(item, index) in checkGroupOptions"
              :key="index"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="appo_wrap">
      <el-table
        :data="tableData"
        :span-method="objectSpanMethod"
        border
        stripe
        style="width: 100%;"
        class="ky-table">
        <el-table-column
          prop="checkroom"
          label="机房"
          width="100">
        </el-table-column>
        <el-table-column
          prop="week"
          label="星期"
          width="100">
        </el-table-column>
        <el-table-column
          prop="total"
          label="全天总数"
          width="100">
        </el-table-column>
        <el-table-column
          v-for="(fld, i) in fields"
          :key="i"
          :label="fld.label"
          class-name="ipt_wrap"
        >
          <template slot-scope="scope">
            <el-input type="text" size="small" v-model="tableData[scope.$index][fld.prop]" @change="appoNumberChange(scope.$index)"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="btns ky-mt20">
      <el-button size="small" type="primary" @click="sendSubmit">提交</el-button>
      <el-button size="small" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script>
import { getCheckGroupList, getDepAreaList, getCheckRoomList, getDepList } from '@/api/api.js'
import { getSeasonDefault, getCheckClassBySeason } from '@/utils/schedule.js'
export default {
  name: '',
  props: {
    hospitalCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      columnlist: [
        { name: '机房', value: 'checkroom' }
      ],
      spanArr: {
        checkroom: []
      },
      pos: {
        WARDNO: []
      },
      formData: {
        hospitalCode: '',
        depArea: '',
        dep: '',
        checkGroup: ''
      },
      rules: {
        checkGroup: [
          { required: true, message: '请选择机房组', triger: 'change' }
        ]
      },
      fields: [
        // { label: '上午班', prop: 'appo' }
      ],
      tableData: [
        // {
        //   checkroom: 'ct1',
        //   label: '星期一',
        //   total: 0, // 总号源数
        //   nodes: [
        //     {
        //       label: '', // 当前时段名称
        //       startTime: '', // 开始时间
        //       endTime: '', // 介绍时间
        //       startNum: 1, // 当前时段起始号源
        //       number: 0 // 号源数
        //     }
        //   ]
        // }
      ],
      seasonData: [],
      depAreaOptions: [],
      scheduledDepOptions: [],
      checkGroupOptions: [],

      checkroomList: ['CT1', 'CT2', 'CT3'],
      seasonCheckClassList: []
    }
  },
  async created() {
    this.getSeason()
    this.initData()
    this.formData.hospitalCode = this.hospitalCode
    this.$getHospitalList()
    this.getCheckGroupList()

    try {
      await this.getDepAreaOptions()
      this.getScheduledDepOptions()
      this.getCheckGroupList()
    } catch (err) {
      console.log(err)
    }
  },
  methods: {
    appoNumberChange(index) {
      let t = 0
      this.fields.forEach(fld => {
        t = t + this.tableData[index][fld.prop] * 1
      })
      this.tableData[index].total = t
    },
    sendSubmit() {
      console.log('tableData ==== ', JSON.parse(JSON.stringify(this.tableData)))
    },
    reset() {
      this.initData()
    },
    // 根据设置的班次，获取班次对象列表及表单班次展示列数据
    getSeason() {
      const ss = getSeasonDefault()
      if (!ss) return
      const sc = ss.checkClassSettings
      const ssc = []
      const flds = []
      let i = 0
      for (let k in sc) {
        const { startTime, endTime, startNum } = getCheckClassBySeason(sc[k])
        const _c = {
          label: k,
          startTime,
          endTime,
          startNum,
          number: 0
        }
        ssc.push(_c)

        flds.push({
          label: k,
          prop: `number_${i}`
        })
        i++
      }
      this.fields = flds
      this.seasonCheckClassList = ssc
    },
    // 获取周数据
    getWeekData() {
      const weekLabel = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
      const resData = []
      weekLabel.forEach(item => {
        const ro = {
          week: item,
          total: 0
        }
        this.fields.forEach(f => {
          ro[`${f.prop}`] = ''
        })
        resData.push({ ...ro })
      })
      return resData
    },
    initData() {
      const weekData = this.getWeekData()
      console.log('weekData', weekData)
      const dls = []
      this.checkroomList.forEach(cs => {
        weekData.forEach(wdItem => {
          const _obj = {
            checkroom: cs,
            ...wdItem
          }
          dls.push(_obj)
        })
      })
      // console.log('tableData ===', dls)
      this.tableData = dls

      if (this.tableData.length > 0) {
        for (let i = 0; i < this.columnlist.length; i++) {
          this.getSpanArr(this.tableData, this.columnlist[i].value)
        }
      }
    },
    save() {
      console.log('save ~')
    },
    async checkGroupChange() {
      if (this.formData.checkGroup) {
        await this.getCheckRoomList()
        this.initData()
      } else {
        this.tableData = []
      }
    },
    // 获取机房列表，通过机房分组
    getCheckRoomList() {
      const params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep,
        checkGroup: this.formData.checkGroup
      }
      return new Promise(async resolve => {
        await getCheckRoomList(params).then(res => {
          if (res && res.code === 10000) {
            this.checkroomList = res.content.list
            resolve(res)
          }
        })
      })
    },
    // 机房分组（检查分组）
    getCheckGroupList() {
      const params = {
        hospitalCode: this.formData.hospitalCode,
        dep: this.formData.dep
      }
      getCheckGroupList(params).then(res => {
        if (res && res.code === 10000) {
          this.checkGroupOptions = res.content.list
          if (this.checkGroupOptions.length) {
            this.formData.checkGroup = this.checkGroupOptions[0]
            this.checkGroupChange()
          }
        }
      })
    },
    getDepAreaOptions() {
      /* 影像区域列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepAreaList(params).then((res) => {
          if (res.code === 10000) {
            this.depAreaOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea
      }
      return new Promise(async resolve => {
        await getDepList(params).then((res) => {
          if (res.code === 10000) {
            this.scheduledDepOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depAreaOptions = []
          this.scheduledDepOptions = []
          this.checkGroupOptions = []
          this.formData.depArea = ''
          this.formData.dep = ''
          this.formData.checkGroup = ''
          try {
            await this.getDepAreaOptions()
            this.getScheduledDepOptions()
            this.getCheckGroupList()
          } catch (err) {
            console.log(err)
          }
          break
        case 'depArea':
          this.scheduledDepOptions = []
          this.checkGroupOptions = []
          this.formData.dep = ''
          this.formData.checkGroup = ''
          try {
            await this.getScheduledDepOptions()
            this.getCheckGroupList()
          } catch (err) {
            console.log(err)
          }
          break
        case 'dep':
          this.checkGroupOptions = []
          this.formData.checkGroup = ''
          try {
            this.getCheckGroupList()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    // 相同行的合并
    getSpanArr(data, column) {
      // 清空
      this.spanArr[column] = []
      this.pos[column] = []

      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr[column].push(1)
          this.pos[column] = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i][column] === data[i - 1][column]) {
            this.spanArr[column][this.pos[column]] += 1
            this.spanArr[column].push(0)
          } else {
            this.spanArr[column].push(1)
            this.pos[column] = i
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        const _row = this.spanArr[column.property][rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.payment-box{
    padding: 24px;
    .el-form{
        margin-top: 20px;
        .el-input{
            width: 180px;
        }
    }
}
.appo_wrap{
  /deep/ .el-table__body-wrapper{
    max-height: 400px;
    overflow-y: auto;
  }
  // /deep/ .ipt_wrap{
  //   padding: 0px;
  //   .cell{
  //     padding: 0px;
  //   }
  //   .el-input__inner{
  //     border: none;
  //     background-color: rgba(255,255,255,0);
  //   }
  // }
}
</style>
